﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCmd;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using LitJson;
using UnityEngine;
using System.IO;
using System.Collections;

/// <summary>
/// 客户端抽象的服务器
/// </summary>
public class ServerInClient : IServer
{
    //private string _serverIP = "192.168.22.5"
    private string _serverIP;// = "192.168.20.105";
    private int _port;// = 4096;

    IClient _client;

    Socket _socket;

    Thread _reciveThread;
    Timer _reciveTimer;
    NetworkStream _ns;

    // 数据流
    MemoryStream _dataStream = new MemoryStream();
    // 刚收到的，还未处理的消息包的列表
    List<Package> _recivedPackageList = new List<Package>();

    public ServerInClient()
    {
        _serverIP = MiscTable.instance[1].IP;
        _port = MiscTable.instance[1].Port;
    }

    public void Connect(IClient net)
    {
        _client = net;
        if (_socket == null)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        // 已结连接了
        if (_socket.Connected) { return; }

        try
        {
            var endPoint = new IPEndPoint(IPAddress.Parse(_serverIP), _port);
            Debug.Log("正在连接服务器：" + endPoint);
            _socket.Connect(endPoint);
            Debug.Log("连接服务器成功~~");
            //_reciveThread = new Thread(reciveDataThread);
            //_reciveThread.Start();
            _reciveTimer = TimerMgr.instance.CreateFrameBaseTimerAndStart(reciveDataThread);
        }
        catch(Exception ex)
        {
            Debug.Log("连接服务器失败！" + ex.Message);
            stopRecive();
        }
    }

    /// <summary>
    /// 停止接收
    /// </summary>
    private void stopRecive()
    {
        if (_reciveTimer != null) { _reciveTimer.Stop(); }
        if (_reciveThread != null) { _reciveThread.Abort(); }
    }

    public void UnConnect(IClient net)
    {
        _client = null;
        stopRecive();
        _socket.Close();
    }

    public bool IsConnected()
    {
        if (_socket != null )
        { return _socket.Connected; }

        return false;
    }
    
    private void reciveDataThread()
    {
        //while(true)
        {
            try
            {
                reciveData();
            }
            catch (Exception ex)
            {
                Debug.Log("接收数据异常，连接手动断开，" + ex.Message);
                Debug.Log("错误堆栈" + ex.StackTrace);
                stopRecive();
                closeServer();
            }

            //Thread.Sleep(200);
        }
    }

    private void reciveData()
    {
        int len = _socket.Available;
        if (len <= 0)
        {
            return;
        }

        //Debug.Log("收到长度：" + len);
        byte[] bytes = new byte[len];
        int receiveNumber = _socket.Receive(bytes);
        _dataStream.Seek(0, SeekOrigin.End);
        _dataStream.Write(bytes, 0, receiveNumber);
        _dataStream.Seek(0, SeekOrigin.Begin);

        // 分包
        readDataToPackage(_dataStream);

        byte[] left = new byte[_dataStream.RemainingBytes()];
        _dataStream.Read(left, 0, (int)_dataStream.RemainingBytes());
        _dataStream.SetLength(0);     //Clear
        _dataStream.Write(left, 0, left.Length);
    }

    private void readDataToPackage(Stream _dataStream)
    {
        Package.instance.Read(_dataStream, _client);
    }

    private void closeServer()
    {
        _socket.Shutdown(SocketShutdown.Both);
        _socket.Close();
        _socket = null;
    }

    /// <summary>
    /// 向服务器发消息
    /// </summary>
    public void ReciveCmdStr(Type type, string cmdStr)
    {
        // 对客户端透明，不需要在这里写
    }
    /// <summary>
    /// 向服务器发消息
    /// </summary>
    public void ReciveCmd(Cmd cmd)
    {
        var len = _socket.Send(Package.instance.Write(cmd));
    }

    public void SendCmd(NCmd.Cmd cmd)
    {
        // 仅为单机版保留接口
    }

}